import django_filters

from .models import Survey, SurveyAccount, SurveyQuestion


class SurveyFilter(django_filters.rest_framework.FilterSet):
    module = django_filters.CharFilter(empty_value=0, method='filter_module')     # 没传模块id默认返回空数据
    need_corrected = django_filters.BooleanFilter(method='filter_corrected')

    def filter_module(self, queryset, name, value):
        if not value:   # 没传的话, 值为上面的empty_value值
            return queryset.none()
        if value in ['all']:
            return queryset.all()
        return queryset.filter(module_id=value)

    def filter_corrected(self, queryset, name, value):
        if value:
            survey__ids = SurveyQuestion.objects.select_related('survey_qs_cate__survey').\
                filter(type__in=[3, 4]).values_list('survey_qs_cate__survey_id', flat=True)
            return queryset.filter(id__in=survey__ids)
        else:
            return queryset

    class Meta:
        model = Survey
        fields = ['module', 'need_corrected']


class SurveyAccountFilter(django_filters.rest_framework.FilterSet):
    survey = django_filters.CharFilter(empty_value=0, method='filter_survey')     # 没传模块id默认返回空数据
    realname = django_filters.CharFilter(lookup_expr='icontains')

    def filter_survey(self, queryset, name, value):
        if not value:   # 没传的话, 值为上面的empty_value值
            return queryset.none()
        return queryset.filter(survey_id=value)

    class Meta:
        model = SurveyAccount
        fields = ['survey', 'username', 'realname', 'sex', 'faculty_code', 'major_code', 'class_code', 'status']
